#!/usr/bin/env node

var inquirer = require('inquirer');
var shell = require('shelljs');
var push = require('./push').push;
// var send = require('./mail').send;

// 按bugID过滤分支
var argv = process.argv;
var targetBranch = '';
argv.forEach(item => {
  if (item.match(/^\d+$/)) {
    targetBranch = item;
  }

  if(!targetBranch) {
    // 将分支名参数支持 --includes 中的变量
    if(item.includes('--includes=')) {
      targetBranch = item.split('--includes=')[1];
    }
  }
});

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

var exec = require('child_process').exec;

var branchList = {
  type: 'list',
  name: 'branch',
  message: '拉哪个分支?',
  choices: []
};

function __main__() {
  exec('git branch', function (err, stdout) {
    var targetBranchTemp = [];
    var branchArray = stdout.split('\n');
    branchArray = branchArray.map(item => {
      item = item.replace(/\s+/g, '');
      if (targetBranch && item.indexOf(targetBranch) >= 0) {
        targetBranchTemp.push(item);
      }
      return item;
    });
    if (targetBranchTemp.length > 0) {
      branchList.choices = targetBranchTemp;
    } else {
      branchList.choices = branchArray;
    }

    inquirer
      .prompt([branchList])
      .then(answers => answers.branch)
      .then(branch => {
        if (branch === 'develop' || branch === 'master' || branch === 'alpha') {
          console.warn('当前分支不能执行此命令，需要的话请自己手动操作。');
          return;
        }
        var currentBranchName = branch.replace(/\*/, '');
        exec('git checkout alpha', function (err, stdout, stderr) {
          if (stdout) {
            exec(`git merge --no-ff ${currentBranchName}`, function (err, stdout) {
              if (stdout) {
                // console.log(stdout);
                push(currentBranchName, function mail() {
                  // 删除分支
                  exec(`git branch -d ${currentBranchName}`, function (err, stdout, stderr) {
                    if(stdout){
                      stdout.replace(/Deleted branch/,'已删除分支：');
                      console.log(stdout);
                    } else {
                      console.log('出错了，可能需要手动操作。', stderr);
                    }
                  });
                });
              }
            });
          }
        });
      });
  });
}

__main__();